package com.dc.datacollect.utils;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 反射的 Utils 函数集合
 * 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数
 */
@Slf4j
public class ReflectionUtils {


    /**
     * 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter
     *
     * @param object
     * @param fieldName
     * @return
     */
    public static Object getFieldValue(Object object, String fieldName) {
        Field field = getDeclaredField(object, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        }

        makeAccessible(field);

        Object result = null;

        try {
            result = field.get(object);
        } catch (IllegalAccessException e) {
            log.error("getFieldValue:", e);
        }

        return result;
    }

    /**
     * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter
     *
     * @param object
     * @param fieldName
     * @param value
     */
    public static void setFieldValue(Object object, String fieldName, Object value) {
        Field field = getDeclaredField(object, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
        }

        makeAccessible(field);

        try {
            field.set(object, value);
        } catch (IllegalAccessException e) { }
    }


    /**
     * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型
     * 如: public EmployeeDao extends BaseDao<Employee, String>
     *
     * @param clazz
     * @param index
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Class getSuperClassGenricType(Class clazz, int index) {
        Type genType = clazz.getGenericSuperclass();

        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            return Object.class;
        }

        if (!(params[index] instanceof Class)) {
            return Object.class;
        }

        return (Class) params[index];
    }

    /**
     * 通过反射, 获得 Class 定义中声明的父类的泛型参数类型
     * 如: public EmployeeDao extends BaseDao<Employee, String>
     *
     * @param <T>
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getSuperGenericType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredMethod
     *
     * @param object
     * @param methodName
     * @param parameterTypes
     * @return
     */
    public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) {

        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                return superClass.getDeclaredMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {
                //Method 不在当前类定义, 继续向上转型
            }
        }

        return null;
    }

    /**
     * 使 filed 变为可访问
     *
     * @param field
     */
    public static void makeAccessible(Field field) {
        if (!Modifier.isPublic(field.getModifiers())) {
            field.setAccessible(true);
        }
    }

    /**
     * 循环向上转型, 获取对象的 DeclaredField
     *
     * @param object
     * @param filedName
     * @return
     */
    public static Field getDeclaredField(Object object, String filedName) {

        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                return superClass.getDeclaredField(filedName);
            } catch (NoSuchFieldException e) {
                //Field 不在当前类定义, 继续向上转型
            }
        }
        return null;
    }

    /**
     * 直接调用对象方法, 而忽略修饰符(private, protected)
     *
     * @param object
     * @param methodName
     * @param parameterTypes
     * @param parameters
     * @return
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     */
    public static Object invokeMethod(Object object, String methodName, Class<?>[] parameterTypes,
                                      Object[] parameters) throws InvocationTargetException {

        Method method = getDeclaredMethod(object, methodName, parameterTypes);

        if (method == null) {
            throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
        }

        method.setAccessible(true);

        try {
            return method.invoke(object, parameters);
        } catch (IllegalAccessException e) {
            log.error("invokeMethod:", e);
        }

        return null;
    }

    /**
     * 拷贝属性 （兼容拷贝原/目标对象为Map）
     *
     * @param source 源
     * @param target 目标
     */
    public static <T> void copyProperties(Object source, Object target) {
        Map<String, Object> sourceMap = null;
        // 判断source是否为Map如何不是将实例转Map
        if (source instanceof Map) {
            sourceMap = (Map<String, Object>) source;
        }else {
            sourceMap = getObjectProperties(source);
        }
        Map<String,Object> targetMap = null;
        for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            // 如果源的属性为空就忽略该项
            if (value == null) {
                continue;
            }
            // 看target是否为Map，如果是直接put，如果不是需要使用反射方法setFieldValue将属性值设置到对应的属性上
            if (target instanceof Map) {

                if (targetMap == null ) {
                    targetMap = (Map<String,Object>)target;
                }
                targetMap.put(key,value);
            }else {
                // 如果设置出错了，忽略，因为如果使用key获取不到对应的属性也会报错，所以忽略就好
                try {
                    setFieldValue(target, key, value);
                }catch (Exception e) {}
            }

        }

    }

    /**
     * 获取对象属性
     *
     * @param obj obj
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public static Map<String, Object> getObjectProperties(Object obj) {
        Map<String, Object> propertiesMap = new HashMap<>();

        // 获取对象的类
        Class<?> clazz = obj.getClass();

        // 获取对象的所有属性（包括继承的属性）
        Field[] fields = clazz.getDeclaredFields();

        // 遍历属性并将其放入Map
        for (Field field : fields) {
            field.setAccessible(true);  // 设置属性的可访问性（私有属性也可以访问）
            String propertyName = field.getName();

            try {
                Object propertyValue = field.get(obj);
                propertiesMap.put(propertyName, propertyValue);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return propertiesMap;
    }


    /**
     * 创建实例
     *
     * @param clazz clazz
     * @return {@link T}
     */
    public static <T> T createInstance(Class<T> clazz) {
        try {
            Constructor<T> declaredConstructor = clazz.getDeclaredConstructor();
            declaredConstructor.setAccessible(true);
            T instance = declaredConstructor.newInstance();
            return instance;
        }catch (Exception e) {
            return null;
        }
    }
}